﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;

namespace Gollie.Extensions
{
	public static class DateTimeExtensions
	{
		// This presumes that weeks start with Monday.
		// Week 1 is the 1st week of the year with a Thursday in it.

		/*
		public static int WeekNumber(this DateTime dt)
		{
			// Seriously cheat.  If its Monday, Tuesday or Wednesday, then it'll 
			// be the same week# as whatever Thursday, Friday or Saturday are,
			// and we always get those right
			DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(dt);
			if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
			{
				dt = dt.AddDays(3);
			}

			// Return the week of our adjusted day
			return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
		}
		 */

		//Week starts at Sunday, consistent with MySql
		//Week 1 starts at first Sunday in the year
		public static WeekNumber WeekNumber(this DateTime dt)
		{
			int year = dt.Year;

			DateTime yearStart = new DateTime(year, 1, 1);
			int firstDayOfWeek = (int)yearStart.DayOfWeek;
			DateTime firstSunday = yearStart.AddDays((7 - firstDayOfWeek) % 7);
			if (firstSunday > dt)
			{
				year--;
				yearStart = new DateTime(year, 1, 1);
				firstDayOfWeek = (int)yearStart.DayOfWeek;
				firstSunday = yearStart.AddDays((7 - firstDayOfWeek) % 7);
			}

			TimeSpan span = dt - firstSunday;
			int weekNr = (span.Days / 7) + 1;

			return new WeekNumber { Week = weekNr, Year = year };
		}
	}


	public struct WeekNumber
	{
		public int Year { get; set; }
		public int Week { get; set; }
	}
	
}